package com.xuecheng.manage_cms.controller;

import com.xuecheng.api.cms.CmsTemplateControllerApi;
import com.xuecheng.framework.domain.cms.CmsTemplate;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.QueryResponseResult;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.manage_cms.service.CmsTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/cms/template")
public class CmsTemplateController implements CmsTemplateControllerApi {
    @Resource
    private CmsTemplateService cmsTemplateServiceImpl;


    /**
     * 查询所有的Cms模板信息
     *
     * @return 查询出的结果封装成统一返回对象
     */
    @Override
    @GetMapping("/list")
    public QueryResponseResult findList() {
        return cmsTemplateServiceImpl.findAllTemplate();
    }

    /**
     * @param page 第几页
     * @param size 每页显示多少
     *             分页查询所有的Cms模板信息
     * @return 查询出的结果封装成统一返回对象
     */
    @Override
    @GetMapping("/list/{page}/{size}")
    public QueryResponseResult findListByPagination(@PathVariable("page") int page,@PathVariable("size") int size) {
        return cmsTemplateServiceImpl.findListByPagination(page,size);
    }

    /** 上传模板文件
     * @param file              模板文件
     * @param templateName      模板文件名
     * @param templateParameter 模板参数
     * @return 响应结果
     */
    @Override
    @PostMapping("/upload")
    public ResponseResult uploadTemplate(MultipartFile file, @RequestParam("templateName") String templateName, @RequestParam("templateParameter") String templateParameter,@RequestParam("siteId") String siteId) {
        return cmsTemplateServiceImpl.uploadTemplate(file, templateName, templateParameter, siteId);
    }

    /**
     * 根据模板id删除模板
     *
     * @param templateId 模板id
     * @return 操作响应
     */
    @Override
    @DeleteMapping("/delete/{id}")
    public ResponseResult deleteTemplate(@PathVariable("id") String templateId) {
        return cmsTemplateServiceImpl.deleteTemplate(templateId);
    }

    /**
     * 根据模板id导出模板
     *
     * @param templateId 模板id
     * @return 操作字节
     */
    @Override
    @GetMapping("/down/{id}")
    public ResponseResult downTemplate(@PathVariable("id") String templateId, HttpServletResponse response) {
        CmsTemplate cmsTemplate = cmsTemplateServiceImpl.findById(templateId);
        if (cmsTemplate ==null){
            return new ResponseResult(CommonCode.FAIL);
        }
        Map<String,Object> map = cmsTemplateServiceImpl.downTemplate(cmsTemplate);
        if (map.size() == 2){
            byte[] buffer = new byte[1024];
            InputStream fis = null;
            BufferedInputStream bis = null;
            try {
                String fileName = (String) map.get("fileName");
                InputStream inputStream = (InputStream) map.get("inputStream");
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                fis = inputStream;
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    /**
     * 上传模板文件
     *
     * @param file     模板文件
     * @param templateId     模板id
     * @param templateName      模板文件名
     * @param templateParameter 模板参数
     * @param siteId            站点id
     * @return 响应结果
     */
    @Override
    @PostMapping("/update")
    public ResponseResult updateTemplate(MultipartFile file, @RequestParam("templateName") String templateName,@RequestParam("templateId")String templateId, @RequestParam("templateParameter") String templateParameter, @RequestParam("siteId") String siteId) {
        return cmsTemplateServiceImpl.updateTemplate(file, templateId,templateName, templateParameter, siteId);
    }
}
